﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace 图书借阅系统
{

    /// <summary>
    /// Connection 的摘要说明
    /// </summary>
    static public class Connection
    {
        static string strConnection = "server=.; database = BMS;integrated security=true";
        static SqlConnection conn = new SqlConnection(strConnection);
        static public bool TestLink()  //测试数据库是否连接成功，成功返回true，失败返回false。
        {
            bool test = true;
            
            try
            {
                conn.Open();
            }
            catch
            {
                test = false;
            }
            finally
            {
                conn.Close();
            }
            return test;
        }
        static public DataTable getData(string strSelect)   //查询操作，若没要查找到对应的结果集，返回空
        {
            try
            {
                conn.Open();
                SqlDataAdapter dtb = new SqlDataAdapter(strSelect, conn);
                DataTable dtv = new DataTable();
                dtb.Fill(dtv);
                if (dtv.Rows.Count == 0)
                    return null;
                else
                    return dtv;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                conn.Close();
            }
        }
        static public int getNum(string strSelect)   
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(strSelect, conn);
                int n = (int)cmd.ExecuteScalar();
                return n;
            }
            catch (Exception)
            {
                return -1;
            }
            finally
            {
                conn.Close();
            }
        }
        static public object Count(string strCommand,int m)       
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(strCommand, conn);
                SqlDataReader dr = cmd.ExecuteReader();
                object n = null;
                if (dr.Read())
                {   
                     n = (object)dr[m];
                }
                return n;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                conn.Close();
            }
        }
        static public int setData(string strCommand)       //增、删、改操做。若操作失败，返回-1.
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(strCommand, conn);
                int n = cmd.ExecuteNonQuery();
                return n;
            }
            catch (Exception)
            {
                return -1;
            }
            finally
            {
                conn.Close();
            }
        }

    }
}